<%@ page language="java" contentType="text/html; charset=utf8"
	pageEncoding="utf8"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link type="text/css" href="resources/css/jquery-ui.css" 		rel="stylesheet" />
	<link type="text/css" href="resources/css/flexigrid.css" 		rel="stylesheet">
	<link type="text/css" href="resources/css/main.css" 			rel="stylesheet"/>
	<link type="text/css" href="resources/css/ui.jqgrid.css"  media="screen" 	rel="stylesheet" />
	
	<script type="text/javascript" src="resources/jquery.min.js"></script>
	<script type="text/javascript" src="resources/jquery-ui.min.js"></script>
	<script type="text/javascript" src="resources/flexigrid.js"></script>
	
	<script type="text/javascript" src="resources/i18n/grid.locale-en.js" ></script>
	<script type="text/javascript" src="resources/jquery.jqGrid.src.js" ></script>
	<style>
    #toolbar {
        padding: 10px 4px;
    }
    
    #jqUserOrderList {
        font-size: 14px;
    }
    
    </style>
<script type="text/javascript">
$(document).ready(function() { 
	$.ajaxSetup({cache:false});
    var initialized = [false,false];
    
    $(function() {
        $( "#mainMenu" ).tabs(
        		{
                    show: function(event, ui)
                        {
                            if(ui.index == 1 && !initialized[0])
                            {
                            	initUsersGrid();
                                initialized[0] = true;
                            }
                            else if(ui.index == 2 && !initialized[1])
                            {
                            	initOrdersGrid();
                                initialized[1] = true;
                            }
                        }
                }		
        );
    });
	
	/* ------------------ BEGIN USERS GRID FUNCTION ----------------- */
	function initUsersGrid(){
	    $("#jqUsersList").jqGrid({
	  	jsonReader : {
	  	      root:"rows",
	  	      page: "page",
	  	      total: "total",
	  	      records: "records",
	  	      repeatitems: false,
	  	      id: "0"
	  	   },	  
	      url:'json/entity/userManagement/list',
	      datatype: 'json',
	      mtype: 'GET',
	      colNames:['#', 'Имя.Фамилия', 'Логин', 'Емэйл', 'Фирма','Тип','#', 'Менеджер','Менеджер','Регистрация',''], 
	      colModel :[ 
	        {name:'id', 			index:'id', 					width:10, sortable:false },
	        {name:'name',			index:'name', 					width:85, sortable:false },
	        {name:'username',		index:'username', 				width:80, sortable:false, fixed:true },
	        {name:'email',		index:'email', 					width:100, sortable:false },
	        {name:'company',		index:'company', 				width:160, sortable:false },
	        {name:'userType.denumirea_ru',		index:'userType.denumirea_ru',	width:60, sortable:false },
	        {name:'enabled',		index:'enabled',				width:20, sortable:false, fixed:true,
	      	  formatter: enabledFormatter},
	        {name:'manager.name',	 index:'manager.name',			width:40, sortable:false, hidden:true },
	        {name:'manager.id',	 index:'manager.id',			width:80, 
	      	  editable:true,
	      	  edittype:'select', formatter:'select',
	      	  editoptions:{value:"10:Sveatollav Covaliov;11:Oxana Chirita;12:Marina Casapu;14:Dmitrii Bordian;15:Cristina Toma"}},
	      	{name:'regDate',		index:'regDate', 				width:50, sortable:false },
			{name:'id', 					index:'id', 	width:60, align:'center', fixed:true, sortable:false, resize:false, 
	         	  formatter:'actions', formatoptions:{keys:true}}    	  
	      ],
	      pager: '#pager',
	      toppager: false,
	      rowNum:100,
	      rowList:[10,20,30,50,100],
	      sortname: 'id',
	      sortorder: 'asc',
	      viewrecords: true,
	      gridview: true,
	      autowidth: true,
	      shrinkToFit: true,
	      height: 'auto',
	      caption: 'Список ползователей',
	      search: true,
	      editurl : 'json/entity/userManagement/edit'
	    });   
	};
	/* ------------------ BEGIN USERS GRID FUNCTION ----------------- */


	/* ------------------ BEGIN ORDERS GRID FUNCTION ----------------- */		
	function initOrdersGrid(){
		  $("#jqUserOrderList").jqGrid({
			jsonReader : {
			      root:"rows",
			      page: "page",
			      total: "total",
			      records: "records",
			      repeatitems: false,
			      id: "0"
			   },	  
		    url:'json/entity/userOrder/admin',
		    datatype: 'json',
		    mtype: 'POST',
		    colNames:['№','Фирма' ,'Номер заказа', 'Дата заказа', '','','Статус заказа',''],
		    colModel :[ 
		      {name:'id', 			index:'id', 					width:10, sortable:false },
		      {name:'secUser.company', 			index:'secUser.company', width:100, sortable:false },
		      {name:'orderNr',		index:'orderNr', 				width:30, sortable:false },   
		      {name:'orderDate',	index:'orderDate', 				width:30},
		      {name:'id', 			index:'id', 					width:90, align:'center', fixed:true, sortable:false, resize:false, formatter: approveFormatter},
		      {name:'id', 			index:'id', 					width:90, align:'center', fixed:true, sortable:false, resize:false, formatter: rejectFormatter},    	  
		      {name:'orderStatus',	index:'orderStatus', 			width:100, align:'center',fixed:true, resize:false, formatter: statusFormatter },
		      {name:'id', 			index:'id', 					width:80, align:'center', fixed:true, sortable:false, resize:false, hidden: true}
		    ],
		    pager: '#pager',
		    toppager: false,
		    rowNum:10,
		    rowList:[10,20,30],
		    sortname: 'id',
		    sortorder: 'asc',
		    viewrecords: true,
		    gridview: true,
		    autowidth: true,
		    shrinkToFit: true,
		    height: 'auto',
		    caption: 'User Orders',
		    search: true,
		    postData: 	{ filters:{	
							    	company: 		function() { return $('#pCompany').val(); },
								   	state: 		function() { return $('#pState').val(); },
									dateFrom: 		function() { return $('#pDateFrom').val(); },
								 	dateTo: 		function() { return $('#pDateTo').val(); }
								 	}
			},
		    editurl : 'json/entity/userOrder/edit',
			    subGrid: true,
				caption: "Текущие заказы",
				// define the icons in subgrid
				subGridOptions: {
					"plusicon"  : "ui-icon-triangle-1-e",
					"minusicon" : "ui-icon-triangle-1-s",
					"openicon"  : "ui-icon-arrowreturn-1-e"
				},
			subGridRowExpanded: function(subgrid_id, row_id) {
				var subgrid_table_id, pager_id;
				subgrid_table_id = subgrid_id+"_t";
				pager_id = "p_"+subgrid_table_id;
				$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll' style=' font-size: 16px;'></table>");
				jQuery("#"+subgrid_table_id).jqGrid({
					jsonReader : {
					      root:"rows",
					      page: "page",
					      total: "total",
					      records: "records",
					      repeatitems: false,
					      id: "0"
					   },
					url:'json/entity/userOrderDetail?orderId=' + row_id,
					datatype: 'json',
					colNames: ['№','Инв. №','Фото','Начало', 'Окончание', 'Резервация'],
					colModel: [
						{name:'id',index:'id',width:80,key:true, sortable:false },
						{name:'advertisingRegistry.inventarNr', 	   	index:'advertisingRegistry.inventarNr', 	width:100, sortable:false },
						{name:'photo', 				index:'photo',				width:120, formatter: photoFormatter, sortable:false },      
						{name:'beginCommandDate',index:'beginCommandDate'	,width:120, sortable:false },
						{name:'endCommandDate',index:'endCommandDate'		,width:120, sortable:false },
						{name:'reservationType',index:'reservationType'		,width:180, sortable:false, formatter: reservationFormatter }
					],
				   	rowNum:20,
				   	sortname: 'num',
				    sortorder: 'asc',
				    height: '100%'
				});
			}
		  }); 
	};
	/* ------------------ END ORDERS GRID FUNCTION ----------------- */	
	/* ------------------ BEGIN  F O R M A T T E R S ----------------- */
  function approveFormatter(cellvalue, options, rowObject) {
	  if (rowObject['orderStatus'] == 1 ||rowObject['orderStatus'] == 3 ){
		  var buName = "bt_"+rowObject['id'];
		  var ret ="<input type='button'  value='Утвердить' onclick=\"approveOrder('"+rowObject['id']+"');\" />";
		  return ret;
	  } else {
		  return "";
	  }
	}; 
	
  function rejectFormatter(cellvalue, options, rowObject) {
	  if (rowObject['orderStatus'] == 1 ){
		  var buName = "bt_"+rowObject['id'];
		  var ret ="<input type='button'  value='Отклонить' onclick=\"rejectOrder('"+rowObject['id']+"');\" />";
		  return ret;
	  } else {
		  return "";
	  }
	}; 	
	
	function photoFormatter(cellvalue, options, rowObject) {
		return "<img src='images/small/" + (rowObject['advertisingRegistry'])['inventarNr'] + "' width='120' alt='Photo' title='PHOTO' />";
	}; 
	
	function statusFormatter(cellvalue, options, rowObject) {
		if (cellvalue==0) return "Проект"; 
		if (cellvalue==1) return "На утверждение";
		if (cellvalue==2) return "Утверждено";
		if (cellvalue==3) return "Отклонено";
	};	
	
	function reservationFormatter(cellvalue, options, rowObject) {
		if (cellvalue==0) return "Свободно"; 
		if (cellvalue==1) return "Зарезервировано";
		if (cellvalue==2) return "Продано По Договору";
	};	
	
	function photoFormatter(cellvalue, options, rowObject) {
		return "<img src='images/small/" + (rowObject['advertisingRegistry'])['inventarNr'] + "' width='120' alt='Photo' title='PHOTO' />";
	};   

	function priceFormatter(cellvalue, options, rowObject) {
  		return cellvalue + " \u20AC";
	}; 		

	function enabledFormatter(cellvalue, options, rowObject) {
	 	if (rowObject['enabled'] == 1 ){
	  		return "<img src='resources/icons/add.png' width='14' alt='+' title='Activ' />";
	 	}  else {
	  		return "<img src='resources/icons/delete.png' width='14' alt='-' title='Inactiv' />";
	 	}
	};
	/* ------------------ END  F O R M A T T E R S ----------------- */
	
	
}); 
</script>

<script type="text/javascript">
function approveOrder(orderId){
 		//alert('submit=' + orderId);
 		  $.ajax({
	          url : 'json/entity/userOrder/approve',
	          type: 'POST',
	          dataType : "json",
	          data : {
	        	  id : orderId
	          		},
	          success : function(data) {
	        	  $("#jqUserOrderList").trigger("reloadGrid");
	          		},
	          error: function() {
	         	            alert('Error occured');
	         	        }   	          		
      	});
 	};

 	function rejectOrder(orderId){
 		//alert('submit=' + orderId);
 		  $.ajax({
	          url : 'json/entity/userOrder/reject',
	          type: 'POST',
	          dataType : "json",
	          data : {
	        	  id : orderId
	          		},
	          success : function(data) {
	        	  $("#jqUserOrderList").trigger("reloadGrid");
	          		},
	          error: function() {
	         	            alert('Error occured');
	         	        }   	          		
      	});
 	}; 	
	
$(function() {
    $( "#pDateFrom" ).datepicker({
    	dateFormat: "dd.mm.yy",
    	autoSize: true,
        changeMonth: true,
        changeYear: true,
        showOn: "button",
        buttonImage: "resources/css/images/calendar.gif",
        buttonImageOnly: true,
        showButtonPanel: true,
        defaultDate: "+1w",
        onClose: function( selectedDate ) {
            $( "#pDateTo" ).datepicker( "option", "minDate", selectedDate );
        }
    });
    
    $( "#pDateTo" ).datepicker({
    	dateFormat: "dd.mm.yy",
    	autoSize: true,
    	changeMonth: true,
        changeYear: true,
        showOn: "button",
        buttonImage: "resources/css/images/calendar.gif",
        buttonImageOnly: true,
        showButtonPanel: true,
        defaultDate: "+1w",
        onClose: function( selectedDate ) {
            $( "#pDateFrom" ).datepicker( "option", "maxDate", selectedDate );
        }
    });
    
 /* ------------------ FILTERS FUNCTION ----------------- */	  
 	
	$("#btResetFilter").click(function(){
		$("#pCompany").val("");
		$("#pState").attr('value', '-1');
		$("#pDateFrom").val("");
		$("#pDateTo").val("");
		
		$("#jqUserOrderList").trigger("reloadGrid");
	});
	
	$("#btApplyFilter").click(function(){
		$("#jqUserOrderList").trigger("reloadGrid");
	});    
});	


</script>	
	
<title>Заказы он-лайн</title>
</head>
<body title="Admin Main Form">
	<div id="header">
	  <div class="center">
	    <div id="logo">
	    <a href="#">STANDART</a>
	    </div>
	    <span style="float: right">
	    <table summary="main menu" cellpadding="0" border="0" cellspacing="0" class="ThemeMenuBar1MenuOuter">
			<tbody>
			<tr>
				<td><table class="ThemeMenuBar1Menu" cellspacing="0" cellpadding="0" border="0">
					<tbody><tr class="ThemeMenuBar1MainItem">
						<td class="ThemeMenuBar1MainItemText">
						<a href="http://www.standart.md/">
						<img width="32" src='resources/icons/home.png'  />
						</a>
						<a href="http://www.standart.md/contact.php">
						<img width="32" src='resources/icons/mail.png'  />
						</a>
						</td>
					</tr>
					</tbody>
					</table>
				</td>
				<td><table class="ThemeMenuBar1Menu" cellspacing="0" cellpadding="0" border="0">
					<tbody><tr>
						<td>
    		<a href="?language=ru"><img width="32" src='resources/icons/flag_russia.png'  /></a> 
    		<a href="?language=ro"><img width="32" src='resources/icons/flag_moldova.png' /></a>
						</td>
					</tr>
					</tbody>
					</table>
				</td>	
			</tr></tbody></table>	
		</span>
	  </div>
	</div>
	
	<a href="<c:url value="/logout" />"> Выйти из системы </a>
	
	<div id=mainMenu style="font-size: 0.9em;">	
		 <ul>
	        <li><a href="#tabs-1">Отчеты</a></li>
        	<li><a href="#tabs-2">Пользователи</a></li>
        	<li><a href="#tabs-3">Заказы</a></li>
         </ul>
		<div id="tabs-1">
			<center>
				<form action="/reports/1" target="blank" method="get" title="Report 1">
					<table>
						<thead>
							<tr><td colspan="2" align="center">Отчёт </td></tr>
						</thead>
						<tr>
							<td align="right">Parameter 1.1</td>
							<td><input type="text" name="param1" /></td>
						</tr>
						<tr>
							<td align="right">Parameter 1.2</td>
							<td><input type="text" name="param1" /></td>
						</tr>
						<tr>
							<td colspan="2" align="right"><input type="submit" value="Generate" />
							<input type="reset" value="Reset" />
							</td>
						</tr>			
					</table>
				</form>
			<br>
				<form action="/reports/2" target="blank" method="get" title="Report 2">
					<table>
						<thead>
							<tr><td colspan="2" align="center">Report 2</td></tr>
						</thead>
						<tr>
							<td align="right">Parameter 2.1</td>
							<td><input type="text" name="param1" /></td>
						</tr>
						<tr>
							<td align="right">Parameter 2.2</td>
							<td><input type="type" name="param1" /></td>
						</tr>
						<tr>
							<td colspan="2" align="right"><input type="submit" value="Generate" />
							<input type="reset" value="Reset" /></td>
						</tr>						
					</table>
				</form>	
			</center>
		</div> 
		<div id="tabs-2">
			<table id="jqUsersList">
				<tr><td/></tr>
			</table>		
		</div>        
		<div id="tabs-3">
			<div class="ui-jqgrid ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix" style="padding: .2em .2em .2em .2em;" >
				<span class="ui-jqgrid-title" style="font-size: 0.9em;">Фильтрационные параметры</span>
			</div>
			<div id="filtrationPanel" class="ui-userdata ui-state-default" style="padding: .2em .2em .2em .2em;">
			<!-- 	<label for="pCompany">Company :</label> -->
				<input type="text" id="pCompany" class="ui-widget" style="visibility: hidden;">
				
				<label for="pDateFrom">Дата с :</label>
					<input type="text" id="pDateFrom" class="ui-widget">
				<label for="pDateTo">по :</label>
					<input type="text" id="pDateTo" class="ui-widget">
				<label for="pState">Статус :</label>
					<select id="pState" class="ui-widget">
				        <option value="-1">Все статусы</option>
				        <option value="0">Проект</option>
				        <option value="1">На утверждение</option>
				        <option value="2">Утверждено</option>
				        <option value="3">Отклонено</option>
				    </select>
				
				
				
				<input id="btApplyFilter" type="button" value="Отфильтровать">
				<input id="btResetFilter" type="button" value="Очистить фильтр">
			</div>
			
			<div id="pager"></div>
			<table id="jqUserOrderList">
				<tr><td/></tr>
			</table>




		
		</div>         
	</div>
	
<!-- 		    <div id="reports"> -->
<!-- 		        <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p> -->
<!-- 		    </div> -->
<!-- 		    <div id="tabs-2"> -->
<!-- 		        <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p> -->
<!-- 		    </div> -->
<!-- 		    <div id="tabs-3"> -->
<!-- 		        <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p> -->
<!-- 		        <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p> -->
<!-- 		    </div> -->
<!-- 	</div> -->
	

</body>
</html>